package com.yiwei.hdb.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.yiwei.hdb.R;
import com.yiwei.hdb.api.Api;
import com.yiwei.hdb.api.callback.InitAppContract;
import com.yiwei.hdb.api.requestInfo.InitAppRequest;
import com.yiwei.hdb.constant.Const;
import com.yiwei.hdb.constant.UserGlobal;
import com.yiwei.hdb.event.OnHomeEventMsg;
import com.yiwei.hdb.model.GuidePageModel;
import com.yiwei.hdb.model.InitAppModel;
import com.yiwei.hdb.util.ImageUtil;
import com.yiwei.hdb.util.PreferenceUtils;
import com.yiwei.hdb.util.Util;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * Created by Master.Dong on 16/4/10.
 */
public class SplashActivity extends BaseActivity implements InitAppContract.View, AMapLocationListener {

    private static final long TIME = 4000;  //延迟
    @BindView(R.id.splash_iv)
    ImageView splashIv;
    @BindView(R.id.btn_number)
    TextView btnNumber;
    private ImageView imageView;
    private Bitmap bitmap;
    private long startTime;
    private InitAppRequest api;
    public AMapLocationClient mlocationClient;
    //声明mLocationOption对象
    public AMapLocationClientOption mLocationOption = null;
    //    private ACache aCache;
    private boolean isHasData = false;
    private InitAppModel totalData;
    private boolean isFirst = true;
    private CountDownTimer timer = new CountDownTimer(TIME, 1000) {

        @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
        @Override
        public void onTick(long millisUntilFinished) {
            try {
//                btnEarnMoney.setEnabled(false);

                btnNumber.setText("跳过" + (millisUntilFinished / 1000));
            } catch (Resources.NotFoundException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFinish() {
            btnNumber.setText("跳过");
            btnNumber.setEnabled(true);
            if (isHasData) {
                handleThing(totalData);
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash_layout);
        ButterKnife.bind(this);
        initBar();
        api = InitAppRequest.create();
        api.attachView(this);

        imageView = (ImageView) findViewById(R.id.splash_iv);
//        Random random = new Random();
//        int number = random.nextInt(3);
//        switch (number) {
//            case 0:
//                bitmap = ImageUtil.readBitMap(this, R.mipmap.splash_bg);
//                break;
//            case 1:
//                bitmap = ImageUtil.readBitMap(this, R.mipmap.splash_bg_sec);
//                break;
//            case 2:
//                bitmap = ImageUtil.readBitMap(this, R.mipmap.splash_bg_third);
//                break;
//        }
        bitmap = ImageUtil.readBitMap(this, R.mipmap.img_splash_white);
        imageView.setImageBitmap(bitmap);


        api.initDomain();

        setIsNeedCheckLogout(false);
//        aCache = ACache.get(this);


    }

    private void initLocation() {
        mlocationClient = new AMapLocationClient(this);
//初始化定位参数
        mLocationOption = new AMapLocationClientOption();
//设置定位监听
        mlocationClient.setLocationListener(this);
//设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//设置定位间隔,单位毫秒,默认为2000ms
//        mLocationOption.setInterval(2000);
        mLocationOption.setOnceLocation(true);

        mLocationOption.setNeedAddress(true);
//设置定位参数
        mlocationClient.setLocationOption(mLocationOption);
// 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
// 注意设置合适的定位时间的间隔（最小间隔支持为1000ms），并且在合适时间调用stopLocation()方法来取消定位请求
// 在定位结束后，在合适的生命周期调用onDestroy()方法
// 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
//启动定位
        mlocationClient.startLocation();
    }

    private void startActivity(boolean selectPoi) {
        if (UserGlobal.getIsOpenGuesture() && isSetGuesture() && UserGlobal.checkLogin()) {
            Intent intent = new Intent(SplashActivity.this, MainActivityNew.class);
            intent.putExtra("is_select", selectPoi);
            intent.putExtra("gesture", true);
            intent.putExtra("is_init", isHasData);
            startActivity(intent);
            overridePendingTransition(R.anim.splash_in, R.anim.splash_out);
            Util.startActivity(this, GestureLoginActivity.class);
            finish();
        } else {
            Intent intent = new Intent(SplashActivity.this, MainActivityNew.class);
            intent.putExtra("is_select", selectPoi);
            intent.putExtra("is_init", isHasData);
            startActivity(intent);
            overridePendingTransition(R.anim.splash_in, R.anim.splash_out);
            finish();
        }

    }
//        doJump();

//    private void doJump() {
////        通过修改不同的key，有很多个手势密码
//        String gesturePassword = aCache.getAsString(Const.GESTURE_PASSWORD);
//        if (gesturePassword == null || "".equals(gesturePassword)) {
//            Intent intent = new Intent(SplashActivity.this, CreateGestureActivity.class);
//            startActivity(intent);
//            finish();
//        } else {
//            Intent intent = new Intent(SplashActivity.this, GestureLoginActivity.class);
//            startActivity(intent);
//            finish();
//        }
//    }

    /**
     * 初始化app
     */
    private void appInit() {
        api.initApp();

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        api.detachView();
        if (mlocationClient != null) {
            mlocationClient.unRegisterLocationListener(this);
            mlocationClient.onDestroy();
            mlocationClient = null;
        }
        try {
            if (bitmap != null && !bitmap.isRecycled()) {
                bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
                imageView.setImageResource(0);
                bitmap.recycle();
                bitmap = null;
                System.gc();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void showError() {
        isHasData = true;
//        startActivity();
    }

    @Override
    public void complete() {

    }

    @Override
    public void onRequestStart() {

    }

    @Override
    public void initAppSuccess(InitAppModel model) {
        isHasData = true;
        try {
            UserGlobal.saveInitInfo(model);
            totalData = model;

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void initDomainSuccess(String url) {
        Const.SERVER_API_URL = url;
        Api.getChangeUrl();
        startTime = System.currentTimeMillis();

        checkPermission(new CheckPermListener() {
                            @Override
                            public void superPermission() {
                                PreferenceUtils.putBoolean(Application.getInstance(), "is_locat", true);
                                initLocation();
                                timer.start();
                            }

                            @Override
                            public void superReject() {
//                                timer.start();
//                                PreferenceUtils.putBoolean(Application.getInstance(), "is_locat", false);
//                                appInit();
                            }
                        }, R.string.location_p, R.string.get_location,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.READ_PHONE_STATE);
    }


    private synchronized void handleThing(InitAppModel model) {
        if (!isFirst) {
            isFirst = false;
            return;
        }
        if (model == null || model.getGuide_page() == null) {
            startActivity(false);
            return;
        }

        if (!PreferenceUtils.getBoolean(SplashActivity.this, "startFirst", false)) {

//            PreferenceUtils.putBoolean(SplashActivity.this, "startFirst", true);

            PreferenceUtils.putLong(SplashActivity.this, "update_time", System.currentTimeMillis());

            Intent intent = new Intent(SplashActivity.this, GuideActivity.class);
            GuidePageModel pageModel = model.getGuide_page();
            intent.putExtra("GuidePage", pageModel);

            startActivity(intent);
            overridePendingTransition(R.anim.splash_in, R.anim.splash_out);
            finish();

        } else {

            startActivity(false);
        }
//        Intent intent = new Intent(SplashActivity.this, GuideActivity.class);
//        GuidePageModel pageModel = model.getGuide_page();
//        intent.putExtra("GuidePage", pageModel);
//        startActivity(intent);
//        overridePendingTransition(R.anim.splash_in, R.anim.splash_out);
//        finish();
    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (amapLocation != null) {
            PreferenceUtils.putDouble(Application.getInstance(), Const.KEY.LAT, amapLocation.getLatitude());
            PreferenceUtils.putDouble(Application.getInstance(), Const.KEY.LNG, amapLocation.getLongitude());
            if (amapLocation.getErrorCode() == 0) {
                //定位成功回调信息，设置相关消息
                PreferenceUtils.putString(this, Const.KEY.LOCATION_ADDRESS, amapLocation.getCity());
                appInit();
            } else {
                appInit();
                //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
            }
        }
    }

    @OnClick({R.id.btn_number})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_number:
                startActivity(false);
                break;

        }
    }
}
